// 图库管理API服务 - 支持MongoDB
const express = require('express');
const router = express.Router();
const Gallery = require('../models/Gallery');
const GalleryMongo = require('../models/GalleryMongo');
const { authenticateToken } = require('../middleware/auth');
const Authorization = require('../middleware/authorization');

// 根据配置选择数据库类型
const useMongoDB = process.env.USE_MONGODB === 'true';

// 获取图库模型
function getGalleryModel() {
    return useMongoDB ? GalleryMongo : Gallery;
}

// 获取图库列表
router.get('/gallery', authenticateToken, async (req, res) => {
    try {
        const { 
            page = 1, 
            limit = 20, 
            category, 
            usageType, 
            search, 
            isActive = true 
        } = req.query;

        const GalleryModel = getGalleryModel();
        const result = await GalleryModel.findAll({
            page: parseInt(page),
            limit: parseInt(limit),
            category,
            usageType,
            search,
            isActive: isActive === 'true'
        });

        res.json({
            success: true,
            data: result.data,
            pagination: result.pagination
        });
    } catch (error) {
        console.error('获取图库列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取图库列表失败'
        });
    }
});

// 获取图片详情
router.get('/gallery/:id', authenticateToken, async (req, res) => {
    try {
        const GalleryModel = getGalleryModel();
        const gallery = await GalleryModel.findById(req.params.id);
        
        if (!gallery) {
            return res.status(404).json({
                success: false,
                message: '图片不存在'
            });
        }

        res.json({
            success: true,
            data: gallery
        });
    } catch (error) {
        console.error('获取图片详情失败:', error);
        res.status(500).json({
            success: false,
            message: '获取图片详情失败'
        });
    }
});

// 创建图片
router.post('/gallery', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const GalleryModel = getGalleryModel();
        const galleryData = {
            ...req.body,
            createdBy: req.user.userId
        };

        // 验证必填字段
        if (!galleryData.name || !galleryData.imageUrl) {
            return res.status(400).json({
                success: false,
                message: '图片名称和URL为必填项'
            });
        }

        const gallery = await GalleryModel.create(galleryData);

        res.status(201).json({
            success: true,
            message: '图片创建成功',
            data: gallery
        });
    } catch (error) {
        console.error('创建图片失败:', error);
        res.status(500).json({
            success: false,
            message: '创建图片失败'
        });
    }
});

// 更新图片
router.put('/gallery/:id', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const GalleryModel = getGalleryModel();
        const gallery = await GalleryModel.findById(req.params.id);
        
        if (!gallery) {
            return res.status(404).json({
                success: false,
                message: '图片不存在'
            });
        }

        const updatedGallery = await GalleryModel.update(req.params.id, req.body);

        res.json({
            success: true,
            message: '图片更新成功',
            data: updatedGallery
        });
    } catch (error) {
        console.error('更新图片失败:', error);
        res.status(500).json({
            success: false,
            message: '更新图片失败'
        });
    }
});

// 删除图片
router.delete('/gallery/:id', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const GalleryModel = getGalleryModel();
        const gallery = await GalleryModel.findById(req.params.id);
        
        if (!gallery) {
            return res.status(404).json({
                success: false,
                message: '图片不存在'
            });
        }

        const deleted = await GalleryModel.delete(req.params.id);

        if (deleted) {
            res.json({
                success: true,
                message: '图片删除成功'
            });
        } else {
            res.status(500).json({
                success: false,
                message: '图片删除失败'
            });
        }
    } catch (error) {
        console.error('删除图片失败:', error);
        res.status(500).json({
            success: false,
            message: '删除图片失败'
        });
    }
});

// 获取特定用途的图片
router.get('/gallery/usage/:type', async (req, res) => {
    try {
        const { type } = req.params;
        const { limit = 10 } = req.query;

        // 验证用途类型
        const validTypes = ['carousel', 'featured', 'about', 'blog', 'product', 'general'];
        if (!validTypes.includes(type)) {
            return res.status(400).json({
                success: false,
                message: '无效的用途类型'
            });
        }

        const GalleryModel = getGalleryModel();
        const galleries = await GalleryModel.findByUsageType(type, parseInt(limit));

        res.json({
            success: true,
            data: galleries
        });
    } catch (error) {
        console.error('获取用途图片失败:', error);
        res.status(500).json({
            success: false,
            message: '获取用途图片失败'
        });
    }
});

// 批量更新排序
router.post('/gallery/sort', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const { sortData } = req.body;

        if (!Array.isArray(sortData) || sortData.length === 0) {
            return res.status(400).json({
                success: false,
                message: '排序数据无效'
            });
        }

        const GalleryModel = getGalleryModel();
        await GalleryModel.updateSortOrder(sortData);

        res.json({
            success: true,
            message: '排序更新成功'
        });
    } catch (error) {
        console.error('批量更新排序失败:', error);
        res.status(500).json({
            success: false,
            message: '批量更新排序失败'
        });
    }
});

// 获取分类统计
router.get('/gallery/stats/categories', authenticateToken, async (req, res) => {
    try {
        const GalleryModel = getGalleryModel();
        const stats = await GalleryModel.getCategoryStats();

        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取分类统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取分类统计失败'
        });
    }
});

// 获取使用统计
router.get('/gallery/stats/usage', authenticateToken, async (req, res) => {
    try {
        const GalleryModel = getGalleryModel();
        const stats = await GalleryModel.getUsageStats();

        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取使用统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取使用统计失败'
        });
    }
});

// 上传图片（模拟接口，实际需要集成文件上传服务）
router.post('/gallery/upload', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        // 这里应该集成文件上传服务
        // 目前返回模拟数据
        const { filename, originalname, size, mimetype } = req.body;

        // 模拟文件处理
        const imageUrl = `/uploads/images/${filename}`;
        const thumbnailUrl = `/uploads/thumbnails/${filename}`;
        
        // 模拟图片尺寸检测
        const dimensions = '1920x1080'; // 实际应该通过图片处理获取

        res.json({
            success: true,
            message: '图片上传成功',
            data: {
                imageUrl,
                thumbnailUrl,
                fileSize: size,
                fileType: mimetype,
                dimensions
            }
        });
    } catch (error) {
        console.error('图片上传失败:', error);
        res.status(500).json({
            success: false,
            message: '图片上传失败'
        });
    }
});

module.exports = router;